package team.seekers.skill.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import team.seekers.skill.entity.dao.Question;
import team.seekers.skill.entity.dao.QuestionPicture;
import team.seekers.skill.entity.dao.User;
import team.seekers.skill.entity.query.QuestionQuery;
import team.seekers.skill.entity.vo.fore.add.QuestionAddVO;
import team.seekers.skill.entity.vo.fore.detail.QuestionDetailVO;
import team.seekers.skill.entity.vo.fore.update.QuestionUpdateVO;
import team.seekers.skill.result.Result;
import team.seekers.skill.service.*;
import team.seekers.skill.common.utils.ParamCheckUtils;
import team.seekers.skill.common.utils.SkillUtils;

import java.util.List;
import java.util.Map;

import static team.seekers.skill.result.ResultCode.*;

/**
 * <p>
 *  问题控制器
 * </p>
 *
 * @author hbc
 * @since 2021-02-02
 */
@RestController
@RequestMapping("/api/skill/question")
@Validated
public class QuestionController {
    @Autowired
    private QuestionService questionService;

    @Autowired
    private SkillService skillService;
    @Autowired
    private SectionService sectionService;
    @Autowired
    private UserService userService;
    @Autowired
    private QuestionPictureService questionPictureService;

    //获取提问热度分页
    @PostMapping("/pageQuestionCondition/{current}/{limit}")
    @PreAuthorize("hasRole('ROLE_USER') or hasRole('ROLE_ADMIN')")
    public Result pageQuestionCondition(@RequestBody QuestionQuery questionQuery,
                                        @PathVariable long current,
                                        @PathVariable long limit){
        if(!StringUtils.isEmpty(questionQuery.getSkillId())){
            if(ParamCheckUtils.isNotRightId(questionQuery.getSkillId())){
                return Result.fail(MAIN_GET_FAIL);
            }
        }
        if(!StringUtils.isEmpty(questionQuery.getSectionId())){
            if(ParamCheckUtils.isNotRightId(questionQuery.getSectionId())){
                return Result.fail(MAIN_GET_FAIL);
            }
        }
        Map<String, Object> map = questionService.pageQuestionCondition(current, limit, questionQuery);
        if(map == null){
            return Result.fail(GET_FAIL);
        }
        return Result.success(map);
    }

    @GetMapping("/get/{questionId}")
    @PreAuthorize("hasRole('ROLE_USER') or hasRole('ROLE_ADMIN')")
    public Result getById(@PathVariable String questionId){
        if(ParamCheckUtils.isNotRightId(questionId)){
            return Result.fail(MAIN_GET_FAIL);
        }
        Question byId = questionService.getById(questionId);
        if (byId == null){
            return Result.fail(GET_FAIL);
        }
        QuestionDetailVO questionVO = new QuestionDetailVO();
        BeanUtils.copyProperties(byId,questionVO);
        // 封装用户信息
        User user = userService.getById(byId.getUserId());
        questionVO.setNickname(user.getNickname());
        questionVO.setAvatar(user.getAvatar());
        // 封装图片
        List<String> list = questionPictureService.ListByQuestionId(questionId);
        if(list == null){
            return Result.fail(GET_FAIL);
        }
        questionVO.setPictureList(list);
        return Result.success().data("VO",questionVO);
    }

    @PostMapping("/save")
    @PreAuthorize("hasRole('ROLE_USER') or hasRole('ROLE_ADMIN')")
    public Result saveQuestion(@RequestBody @Validated QuestionAddVO questionVO){
        if(ParamCheckUtils.isNotRightId(questionVO.getSkillId())){
            return Result.fail(ACTION_FAIL);
        }
        Question question = new Question();
        BeanUtils.copyProperties(questionVO,question);
        question.setUserId(SkillUtils.getUserId());
        boolean save = questionService.save(question);
        if(!save){
            return Result.fail(ACTION_FAIL).message("添加失败，请稍后尝试");
        }
        for (String s : questionVO.getPictureList()) {
            QuestionPicture questionPicture = new QuestionPicture();
            questionPicture.setUrl(s);
            questionPicture.setQuestionId(question.getId());
            boolean save1 = questionPictureService.save(questionPicture);
            if(!save1){
                return Result.fail(ACTION_FAIL).message("添加失败，请稍后尝试");
            }
        }
        return Result.success();
    }

    @PutMapping("/update")
    @PreAuthorize("hasRole('ROLE_USER') or hasRole('ROLE_ADMIN')")
    public Result updateQuestion(@RequestBody @Validated QuestionUpdateVO questionVO){
        if(ParamCheckUtils.isNotRightId(questionVO.getId())){
            return Result.fail(PARAM_NOT_VALID);
        }
        Question question = questionService.getById(questionVO.getId());
        if(question == null){
            return Result.fail(ACTION_FAIL).message("更新失败，请稍后重试");
        }
        BeanUtils.copyProperties(questionVO,question);
        question.setUserId(SkillUtils.getUserId());
        boolean update = questionService.updateById(question);
        if(!update){
            return Result.fail(ACTION_FAIL).message("更新失败，请稍后重试");
        }
        // 更新图片
        boolean b = questionPictureService.deleteByQuestionId(question.getId());
        if(!b){
            return Result.fail(ACTION_FAIL).message("更新失败，请稍后重试");
        }
        for (String s : questionVO.getPictureList()) {
            QuestionPicture questionPicture = new QuestionPicture();
            questionPicture.setUrl(s);
            questionPicture.setQuestionId(question.getId());
            boolean save1 = questionPictureService.save(questionPicture);
            if(!save1){
                return Result.fail(ACTION_FAIL).message("更新失败，请稍后尝试");
            }
        }
        return Result.success();
    }

    @DeleteMapping("/delete/{questionId}")
    @PreAuthorize("hasRole('ROLE_USER') or hasRole('ROLE_ADMIN')")
    public Result deleteQuestion(@PathVariable String questionId){
        if(ParamCheckUtils.isNotRightId(questionId)){
            return Result.fail(PARAM_NOT_VALID);
        }
        boolean b = questionService.removeById(questionId);
        if (!b){
            return Result.fail(ACTION_FAIL);
        }
        // 删除所有图片
        boolean b1 = questionPictureService.deleteByQuestionId(questionId);
        if(!b1){
            return Result.fail(ACTION_FAIL);
        }
        return Result.success();
    }
}

